<?php

namespace Framework\Foundation\Event;

use Psr\EventDispatcher\ListenerProviderInterface;

class ListenerProvider implements ListenerProviderInterface
{
    protected $eventListeners = [];

    public function __construct($eventListeners = [])
    {
        $this->eventListeners = $eventListeners;
    }

    public function pushListener(string $event, $listener)
    {
        if (!isset($this->eventListeners[$event])) {
            $this->eventListeners[$event] = [];
        }
        array_push($this->eventListeners[$event], $listener);
    }

    public function getListenersForEvent(object $event): iterable
    {
        $eventName = get_class($event);

        if (!isset($this->eventListeners[$eventName])) {
            return [];
        }

        return $this->concreteListeners($eventName);
    }

    public function concreteListeners($eventName)
    {
        foreach ($this->eventListeners[$eventName] as $k => $v) {
            if (is_string($v)) {
                $this->eventListeners[$eventName][$k] = new $v;
            }
        }

        return $this->eventListeners[$eventName];
    }
}
